package ar.edu.unsam.algo3.plantasvszombies.wicket

import ar.edu.unsam.algo3.plantasvszombies.dominio.Fila
import ar.edu.unsam.algo3.plantasvszombies.dominio.Jardin
import ar.edu.unsam.algo3.plantasvszombies.dominio.JardinZen
import ar.edu.unsam.algo3.plantasvszombies.dominio.Planta
import org.apache.wicket.ajax.AjaxRequestTarget
import org.apache.wicket.markup.html.basic.Label
import org.apache.wicket.markup.html.form.Form
import org.apache.wicket.markup.html.panel.FeedbackPanel
import org.apache.wicket.markup.html.panel.Panel
import org.apache.wicket.model.CompoundPropertyModel
import org.uqbar.commons.model.UserException
import org.uqbar.wicket.xtend.WicketExtensionFactoryMethods
import org.uqbar.wicket.xtend.XAjaxLink
import org.uqbar.wicket.xtend.XListView

class FilaPanel extends Panel {
	extension WicketExtensionFactoryMethods = new WicketExtensionFactoryMethods
	var Fila fila
	var feedbackPanel = new FeedbackPanel("feedbackPanel")

	new(String id, Fila model) {
		super(id)
		defaultModel = fila.asCompoundModel
		val Form<Fila> formFila = new Form<Fila>("formFila", new CompoundPropertyModel<Fila>(model))

		fila = model
		if(fila.jardinZen == null) init
		agregarDatos(formFila)
		agregarTabla(formFila)
		agregarAcciones(formFila)

		addChild(formFila)
	}

	def init() {
		fila.jardinZen = new JardinZen
		fila.jardin = new Jardin
	}

	def agregarDatos(Form<Fila> form) {
		form.addChild(new Label("tipo", fila.jardinZen.tipo))
		form.addChild(new Label("lugaresDisponibles"))
		feedbackPanel.outputMarkupId = true
		form.addChild(feedbackPanel)
	}

	def agregarTabla(Form<Fila> form) {
		val listView = new XListView("plantas")
		listView.populateItem = [ item |
			item.model = item.modelObject.asCompoundModel
			item.addChild(new Label("nombre"))
			item.addChild(new Label("defensa"))
			item.addChild(new Label("ataque"))
			item.addChild(
				new XAjaxLink("eliminar") => [
					onClick = [ target |
						fila.eliminarPlanta(item.modelObject)
						target.add(form)
					]
				])
		]
		form.addChild(listView)
	}

	def agregarAcciones(Form<Fila> form) {
		val listView = new XListView("jardinZen.plantines")
		listView.populateItem = [ item |
			item.model = item.modelObject.asCompoundModel
			val miBoton = new XAjaxLink<Object>("seleccionar") => [
				onClick = [ target |
					agregarPlanta(target, item.modelObject, form)
				]
			]
			miBoton.addChild(new Label("nombre"))
			item.addChild(miBoton)
		]
		form.addChild(
			new XAjaxLink("salir") => [
				onClick = [ target |
					target.add(this.parent)
				]
			])
		form.addChild(listView)
	}

	def agregarPlanta(AjaxRequestTarget target, Planta planta, Form<?> form) {
		try {
			fila.agregarPlanta(planta)
			target.add(form)

		} catch (UserException e) {
			error(e.message)
			target.add(feedbackPanel)
		}
	}

}
